import { Singleton } from '../../framework/common/Singleton';
import type { RemoteData, RemoteDataType } from '../../../../shares/sharesApp';

export class RemoteMgr extends Singleton<RemoteMgr>() {
  constructor() {
    super();
    console.log('(Server) RemoteMgr constructor');
  }

  private static _instance: RemoteMgr | null = null;

  public static getInstance(): RemoteMgr {
    if (!this._instance) {
      this._instance = new RemoteMgr();
    }
    return this._instance;
  }

  /**
   * 启动远程管理器 / Start the remote manager
   */
  public start(): void {
    console.log('(Server) RemoteMgr start');
    this.bindEvents();
  }

  /**
   * 绑定事件 / Bind events
   */
  private bindEvents(): void {
    remoteChannel.onServerEvent(({ tick, entity, args }) => {
      this.onServerEvent(tick, entity, args);
    });
  }

  /**
   * 服务器事件处理 / Server event handler
   * @param tick 服务器事件帧 / Server event frame
   * @param entity 玩家实体 / Player entity
   * @param args 参数 / Arguments
   */
  private onServerEvent(
    tick: number,
    entity: GamePlayerEntity,
    args: RemoteDataType
  ): void {
    // 处理服务器事件逻辑
  }

  /**
   * 发送数据给玩家 / Send data to player
   * @param entities 玩家实体 / Player entity
   * @param data 数据 / Data
   */
  public send<T>(
    entities: GamePlayerEntity | GamePlayerEntity[],
    data: RemoteData<T>
  ) {
    remoteChannel.sendClientEvent(entities, data);
  }

  /**
   * 发送数据给所有玩家 / Send data to all players
   * @param data 数据 / Data
   */
  public sendAll<T>(data: RemoteData<T>) {
    remoteChannel.broadcastClientEvent(data);
  }
}
